#!/usr/bin/env python
# coding: utf-8

import random, os, sys, time

if __name__ == "__main__":
    strings_num = int(sys.argv[1])

    assert os.system('gcc -g3 -w 2013-04-15-a.c -o z_function') == 0, 'compilation failed'
    assert os.system('gcc -g3 -w 2013-04-15-b.c -o pref_function') == 0, 'compilation failed'
    assert os.system('gcc -g3 -w 2013-04-18-c.c -o pref_to_z') == 0, 'compilation failed'

    for i in range(strings_num):
        string = ''
        N = random.randint(2, 10 ** 5)
        alpha_size = random.randint(1, 26)
        print('test #{0}, string length = {1}, alphabet size = {2}'.format(i, N, alpha_size))
        for j in range(N):
            string += chr(random.randint(ord('a'), ord('a') + alpha_size))
        in_file = open('/tmp/input-str.txt', 'w')
        in_file.write(string + '\n')
        in_file.flush()
        in_file.close()

        start_time = time.time()
        os.system('./z_function </tmp/input-str.txt >/tmp/z.out')
        os.system('./pref_function </tmp/input-str.txt >/tmp/pref.out')

        in_file = open('/tmp/input.txt', 'w')
        pref_file = open('/tmp/pref.out', 'r')
        z_file = open('/tmp/z.out', 'r')
        pref_function = pref_file.readline().split()
        pref_function.insert(0, '0')
        in_file.write(str(len(pref_function)) + '\n' + \
                      ' '.join(pref_function) + '\n')
        in_file.flush()
        in_file.close()

        os.system('./pref_to_z </tmp/input.txt >/tmp/answer.txt')
        end_time = time.time()

        z_function = z_file.readline().split()
        z_function.insert(0, str(len(z_function) + 1))
        answer_file = open('/tmp/answer.txt', 'r')
        answer = answer_file.readline().split()

        pref_file.close()
        z_file.close()
        answer_file.close()

        if z_function != answer:
            print('test #{0} FAILED'.format(i))
            break
        else:
            print('test #{1} passed in {0} secs'.format(end_time - start_time, i))

        for filename in ('/tmp/input-str.txt',
                         '/tmp/z.out',
                         '/tmp/pref.out',
                         '/tmp/input.txt',
                         '/tmp/answer.txt'):
            os.unlink(filename)
